<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Log;

class DiagnoseTableIssue extends Command
{
    protected $signature = 'diagnose:table-issue {tableName}';
    protected $description = '诊断表存在性检测问题';
    
    public function handle()
    {
        $tableName = $this->argument('tableName');
        //die($tableName);
        
        $this->info("诊断表: {$tableName}");
        $this->line(str_repeat('-', 50));
        
        // 方法1: 使用 Schema::hasTable()
        $this->info("1. 使用 Schema::hasTable('{$tableName}')");
        $schemaResult = Schema::hasTable($tableName);
        $this->info("   结果: " . ($schemaResult ? '存在' : '不存在'));
        
        // 方法2: 使用原始 SQL 查询
        $this->info("2. 使用原始 SQL 查询");
        try {
            $tables = DB::select("SHOW TABLES LIKE '{$tableName}'");
            $sqlResult = count($tables) > 0;
            $this->info("   结果: " . ($sqlResult ? '存在' : '不存在'));
            $this->info("   找到的表: " . json_encode($tables));
        } catch (\Exception $e) {
            $this->error("   查询失败: " . $e->getMessage());
        }
        
        // 方法3: 检查信息模式
        $this->info("3. 检查 information_schema");
        try {
            $result = DB::select("
                SELECT TABLE_NAME 
                FROM INFORMATION_SCHEMA.TABLES 
                WHERE TABLE_SCHEMA = DATABASE() 
                AND TABLE_NAME = '{$tableName}'
            ");
            $infoSchemaResult = count($result) > 0;
            $this->info("   结果: " . ($infoSchemaResult ? '存在' : '不存在'));
        } catch (\Exception $e) {
            $this->error("   查询失败: " . $e->getMessage());
        }
        
        // 方法4: 尝试直接查询表
        $this->info("4. 尝试直接查询表");
        try {
            $count = DB::table($tableName)->count();
            $this->info("   结果: 可以查询，记录数: {$count}");
        } catch (\Exception $e) {
            $this->error("   查询失败: " . $e->getMessage());
        }
        
        // 方法5: 检查表名大小写
        $this->info("5. 检查所有相似表名");
        try {
            $allTables = DB::select("SHOW TABLES");
            $matchingTables = [];
            
            foreach ($allTables as $table) {
                $name = $table->{'Tables_in_' . env('DB_DATABASE')};
                if (strtolower($name) === strtolower($tableName)) {
                    $matchingTables[] = $name;
                }
            }
            
            $this->info("   找到的相似表: " . json_encode($matchingTables));
        } catch (\Exception $e) {
            $this->error("   查询失败: " . $e->getMessage());
        }
        
        $this->line(str_repeat('-', 50));
        
        // 总结
        if ($schemaResult) {
            $this->info("总结: Schema::hasTable() 报告表存在");
        } else {
            $this->error("总结: Schema::hasTable() 报告表不存在，但其他方法可能显示不同结果");
        }
        
        return 0;
    }
}
